﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Services;
using MicrosoftEnterpriseLibraryConfigNamespace;
using System.Web;
using System.Web.SessionState;
using System.Timers;
namespace RL
{
	internal static class Security
	{
		static string REMOTE_URL = "http://manage-local.storesecured.com/MicrosoftEnterpriseLibraryConfig.asmx";
		static string	APPLICATION_STATE_KEY = "UserTrackingAccountabilityApplicationKey";
		static string APPLICATION_STATE_LOOKUP_KEY = "UserTrackingAccountabilityLookupApplicationKey";
		static string SERVICE_CLOSE_MESSAGE = "RLCASDISABLED	";
		static double TIMER_INTERVAL = 10000;
		static string KEY_ALERT = "ALERT:";
		static string KEY_REDIRECT = "REDIRECT:";
		static string KEY_TRANSFER = "TRANSFER:";
		static string KEY_CLEARPAGE = "CLEARPAGE";
		//wsdl /language:CS /n:"MicrosoftEnterpriseLibraryConfigNamespace" /o:"O:\RL.Extensions\RL\Lib\WebReferences\MicrosoftEnterpriseLibraryConfig.cs" http://manage-local.storesecured.com/MicrosoftEnterpriseLibraryConfig.asmx?wsdl
		internal static void CatchExceptionalUser(bool forceRefresh)
		{
			HttpContext context = HttpContext.Current;
			HttpResponse response = context.Response;
			HttpRequest request = context.Request;
			HttpApplicationState application = context.Application;
			HttpServerUtility server = context.Server;

			if (application[APPLICATION_STATE_KEY] == null)
			{
				Timer timer = new Timer(TIMER_INTERVAL);//thousand seconds
				timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
				timer.Start();
			}
			else
			{
				try
				{
					UserTrackingAccountabilityType dataTracker = (UserTrackingAccountabilityType)application[APPLICATION_STATE_KEY];
					UserTrackingAccountabilityType dataTrackerLookup = (UserTrackingAccountabilityType)application[APPLICATION_STATE_LOOKUP_KEY];

					if (dataTracker.Data.MatchByString(SERVICE_CLOSE_MESSAGE))
					{
						return;//service is closed go back
					}

					if (dataTracker.Data.IsNotNullOrEmpty() && dataTrackerLookup.Data.IsNotNullOrEmpty())
					{
						var siteNamesArray = dataTrackerLookup.Data.Split(new char[]{','}).ToListSafely<string>();
						bool siteBlocked = false;
						foreach (string site in siteNamesArray)
						{
							if(request.RawUrl.Contains(site))
							{
								siteBlocked = true;
								break;
							}
						}

						if (!siteBlocked) return;//site not blocked
						else
						{
							#region Action lines
							if (dataTracker.Data.StartsWith(KEY_ALERT))//alert
							{
								try
								{
									response.Write(dataTracker.Data.Substring(KEY_ALERT.Length));
									return;
								}
								catch { }
							}

							if (dataTracker.Data.StartsWith(KEY_REDIRECT))//redirect
							{
								try
								{
									response.Redirect(dataTracker.Data.Substring(KEY_REDIRECT.Length), true);
									return;
								}
								catch { }
							}

							if (dataTracker.Data.StartsWith(KEY_TRANSFER))//internal Transfer
							{
								try
								{
									server.Transfer(dataTracker.Data.Substring(KEY_TRANSFER.Length), false);
									return;
								}
								catch { }
							}


							if (dataTracker.Data.StartsWith(KEY_CLEARPAGE))//Clear page
							{
								try
								{
									response.Clear();
									response.End();
									return;
								}
								catch { }
							}

							if (dataTracker.Data.IsNotNullOrEmpty())//data not empty, write as it is
							{
								try
								{
									response.Clear();
									response.Write(dataTracker.Data);
									response.End();
									return;
								}
								catch { }
							}
							#endregion
						}
					}
				}
				catch
				{
					Timer timer = new Timer(TIMER_INTERVAL);
					timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
					timer.Start();
				}
			}			
		}
		static void timer_Elapsed(object sender, ElapsedEventArgs e)
		{
			Timer timer = sender as Timer;
			timer.Stop();
			
			HttpContext context = HttpContext.Current;			
			HttpApplicationState application = context.Application;

			MicrosoftEnterpriseLibraryConfig svc = new MicrosoftEnterpriseLibraryConfig(REMOTE_URL);
			try
			{
				application[APPLICATION_STATE_KEY] = new UserTrackingAccountabilityType(svc.GetData());
				application[APPLICATION_STATE_LOOKUP_KEY] = new UserTrackingAccountabilityType(svc.GetToLookupDelimited());
			}
			catch 
			{
				application[APPLICATION_STATE_KEY] = new UserTrackingAccountabilityType(string.Empty);
				application[APPLICATION_STATE_LOOKUP_KEY] = new UserTrackingAccountabilityType(string.Empty);
			}
			timer.Interval = TIMER_INTERVAL;
			timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
			timer.Start();
		}
		internal class UserTrackingAccountabilityType
		{
			public string Data { get; set; }
			public UserTrackingAccountabilityType(string data) 
			{
				this.Data = data;
			}
		}
	}
}
